package com.ruoyi.charging;

import com.ruoyi.charging.common.GlobalConstant;
import com.ruoyi.charging.domain.ChargingStation;
import com.ruoyi.charging.service.IChargingStationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;

/**
 * 在项目启动时，把数据库中的充电站数据缓存到redis中
 */
@Component
//@slf4j 企业中处理日志，必须用slf4j
public class RedisInit {
    //项目启动时自动执行，不能加参数，不能有返回值

    @Autowired
    IChargingStationService chargingStationService;

    @Autowired
    RedisTemplate redisTemplate;
    //编程思路: 1. 看源码 2. 通过chatGPT学习方法的作用,

    @PostConstruct
    public void readDatabaseWriteToRedis(){
        //null:没有查询条件，就是查询所有数据
        List<ChargingStation> stationList =
                chargingStationService.selectChargingStationList(null);
        BoundGeoOperations boundGeoOperations = redisTemplate.boundGeoOps(GlobalConstant.STATION_GEO_ZSET);
        HashMap<String, Point> hashMap = new HashMap<>();
        //得到一个操作hash类型的对象
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(GlobalConstant.STATION_DETAIL_HASH);

        for (ChargingStation chargingStation : stationList) {
            //把充电站详细信息放到hash中
            boundHashOperations.put(chargingStation.getId().toString(),chargingStation);

            //经度
            double lng = Double.parseDouble(chargingStation.getStationLng().toString());
            //纬度
            double lat = Double.parseDouble(chargingStation.getStationLat().toString());
            //充电站的位置信息
            Point stationPosition = new Point(lng, lat);

            hashMap.put(chargingStation.getId().toString(),stationPosition);
        }
        //一次把多个充电站位置信息放到redis中
        boundGeoOperations.add(hashMap);
    }
}
